package com.xn.app.muying.BroadcastReceiver;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.nostra13.universalimageloader.utils.L;
import com.xn.app.muying.activity.MuYingApplication;
import com.xn.app.muying.activity.ReadHistoryActivity;
import com.xn.app.muying.activity.WebActivity;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;

import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Request;

import static android.content.Context.ACTIVITY_SERVICE;


public class JPushRecevier extends BroadcastReceiver {

    ActivityManager am;
    String mPackageName;
    ComponentName cn;
    public static DBManager db=null;
    Context mContext=null;

    @Override
    public void onReceive(final Context context, Intent intent) {
        mContext=context;
        Bundle bundle = intent.getExtras();
        //处理推送action
        String action = intent.getAction();
        if (action.equals(JPushInterface.ACTION_NOTIFICATION_RECEIVED)) {
            //获取推送下来的标题
            String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            //获取推送下来的内容
            String message = bundle.getString(JPushInterface.EXTRA_ALERT);
            //获取推送下来的json
            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
            //记录当前推送功能模块
            if (extras != null && !extras.equals("") && !extras.equals("null") && !extras.equals("{}")) {
                try {
                    JSONObject jsonObject = new JSONObject(extras);
                    AppConstant.type = jsonObject.optInt("type");
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }
            /**接收到推送下来的通知*/
            //如果不在前台，停止线程刷新时间
            am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            mPackageName = context.getPackageName();
            cn = am.getRunningTasks(1).get(0).topActivity;
            //如果当期要刷新的页面在前台
            if (isAppOnForeground(am, mPackageName)) {
                if ("com.xn.app.muying.activity.ReadHistoryActivity".equals(cn.getClassName())) {
                    Intent i = new Intent(context, ReadHistoryActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.putExtra("data", "1");
                    context.startActivity(i);
                }
            }
        } else if (action.equals(JPushInterface.ACTION_NOTIFICATION_OPENED)) {
            /**用户点击打开了通知*/
            Intent i = null;
            //化验单解读
            if (AppConstant.type == 0) {
                i = new Intent(context, ReadHistoryActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.putExtra("data", "1");
                context.startActivity(i);
            }
            //问答功能
            if (AppConstant.type == 1) {
                db=new DBManager(context);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Request request = new Request.Builder().url(APIMethod.WenDa(db.select("id"))).build();
                            okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                            int code = response.code();
                            final String bodys = response.body().string().replace("\"", "");
                            if (code == 200 || code == 204) {
                                Message msg=new Message();
                                msg.what=1;
                                msg.obj=bodys;
                                loginHandler.sendMessage(msg);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else if (action.equals(JPushInterface.ACTION_MESSAGE_RECEIVED)) {
            /**接收到推送下来的自定义消息*/
        }
    }

    public boolean isAppOnForeground(ActivityManager am, String mPackageName) {
        List<ActivityManager.RunningTaskInfo> tasksInfo = am.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            L.i("top Activity = "
                    + tasksInfo.get(0).topActivity.getPackageName());
            // 应用程序位于堆栈的顶层
            if (mPackageName.equals(tasksInfo.get(0).topActivity
                    .getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                   Intent i = new Intent(mContext, WebActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.putExtra("title", "在线问答");
                    i.putExtra("url", msg.obj.toString());
                    mContext.startActivity(i);
                    break;
                default:
                    break;
            }
        }
    };
}
